package com.eightywork.life.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eightywork.life.R;
import com.eightywork.life.activity.BaseActivity;
import com.eightywork.life.activity.IndexActivity;
import com.eightywork.life.activity.LoginActivity;
import com.eightywork.life.activity.LoginMapActivity;
import com.eightywork.life.activity.MsgListActivity;
import com.eightywork.life.activity.PostActivity;
import com.eightywork.life.activity.RegFirstActivity;
import com.eightywork.life.activity.TelephoneActivity;
import com.eightywork.life.adapter.CommunityListAdapter;
import com.eightywork.life.adapter.CommunityListAdapter.OnTagClickInterface;
import com.eightywork.life.adapter.TagListAdapter;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.imageCache.ImageLoader.onLoadingFinishListener;
import com.eightywork.life.model.Community;
import com.eightywork.life.model.Space;
import com.eightywork.life.model.Tag;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.AndroidUtil;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.widget.ActionsContentView;
import com.eightywork.life.widget.RTPullListView;
import com.eightywork.life.widget.RTPullListView.OnRefreshListener;
import com.eightywork.life.widget.RTPullListView.OnScrollStopAndEndListener;
import com.umeng.analytics.MobclickAgent;

public class CommunityFragment extends BaseFragment implements OnClickListener {
	
	public static final String TAG = CommunityFragment.class.getName();
	private ActionsContentView viewActionsContentView;
	private Activity context;
	private ImageButton menuButton, postButton, telephoneButton, tagButton, regButton, loginButton;
	private ImageView headerbg;
	private Button messageButton;
	private RTPullListView listView;
	private GridView gridView;
	private CommunityListAdapter adapter;
	private TagListAdapter gridAdapter;
	public static List<Community> list = new ArrayList<Community>();
	private List<Tag> tagList = new ArrayList<Tag>();
	private TextView headerTitle, footerText;
	private String xiaoquid, xiaoquname, tagid, picUrl;
	private AsyncTask task, countTask;
	private int page, headerWidth, headerHeight;
	private ViewGroup footView, nodataView;
	private boolean isLoading, tagIsOpen, isRefresh,isLoadCount, isFromPost;
	private ImageLoader imageLoader;
	private LinearLayout ll_footView;
	private CommunityFragment communityFragment;
//	private boolean beginToload;
	public CommunityFragment(Activity context,
			ActionsContentView viewActionsContentView) {
		this.context = context;
		this.viewActionsContentView = viewActionsContentView;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_community, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		initView();
		initData("");
		registerBroadcastReceiver();
	}

	@Override
	public void onResume() {
		super.onResume();
	    MobclickAgent.onResume(getActivity());
	}
	
	
	
	@Override
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(getActivity());
	}

	@Override
	public void onDestroy() {
		if (task != null)
			task.cancel(true);
	
		if (countTask != null)
			countTask.cancel(true);
		getActivity().unregisterReceiver(mReciever);
		super.onDestroy();
	}
	
	
	private void registerBroadcastReceiver(){
		IntentFilter f = new IntentFilter();
		f.addAction(DataService.Constant.FEED_SHOW_BROADCAST);
		getActivity().registerReceiver(mReciever, f);
	}
	
	BroadcastReceiver mReciever= new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent){ 
			String action = intent.getAction();
			if (action.equals(DataService.Constant.FEED_SHOW_BROADCAST)) {
				Bundle bundle = intent.getBundleExtra("bundle");
				Space space = CacheService.getSpace();
				Community communty = new Community();
				communty.setContent(bundle.getString("content"));
				communty.setTitle(bundle.getString("title"));
				communty.setIdtype(bundle.getString("idtype"));
				communty.setTag(bundle.getString("tag"));
				String append_idtype = bundle.getString("append_idtype");
				communty.setAppend_idtype(append_idtype);
				if (!append_idtype.equals("")) {
					communty.setAppend_name(bundle.getString("append_name"));
					communty.setAppend_avatar(bundle.getString("append_avatar"));
					communty.setAppend_text(bundle.getString("append_text"));
					communty.setAppend_title(bundle.getString("append_title"));
					communty.setAppend_image(bundle.getString("append_image"));
					communty.setAppend_idtype(bundle.getString("append_idtype"));
					communty.setAppend_link("");
				}
				int uriImageSize = bundle.getInt("uriSize");
				communty.setUriImageSize(uriImageSize);
				if(uriImageSize > 0) {
					ArrayList alist =bundle.getParcelableArrayList("uri");
					communty.setUriList((List<Uri>)alist.get(0));
				}
				communty.setName(space.getName());
				communty.setAvatar(space.getAvatar());
				communty.setVerifyType(space.getVerifyType());
				communty.setDateline(new Date().getTime()/1000L + "");
				list.add(0,communty);
				adapter.notifyDataSetChanged();
			}
		}
	};

	private void initView() {
		headerTitle = (TextView) getView().findViewById(R.id.header_title);
		headerTitle.setOnClickListener(this);
		menuButton = (ImageButton) getView().findViewById(R.id.button_left);
		menuButton.setOnClickListener(this);
		postButton = (ImageButton) getView().findViewById(R.id.button_right);
		postButton.setOnClickListener(this);
		telephoneButton = (ImageButton) getView().findViewById(
				R.id.button_telephone);
		telephoneButton.setOnClickListener(this);
		listView = (RTPullListView) getView().findViewById(R.id.listView1);
		footView = (ViewGroup) getActivity().getLayoutInflater().inflate(
				R.layout.item_footer, null);
		nodataView = (ViewGroup) getActivity().getLayoutInflater().inflate(
				R.layout.item_footer_nodata, null);
		footerText = (TextView) nodataView.findViewById(R.id.textView1);
		View view = listView.getHeaderView();
		gridView = (GridView) view.findViewById(R.id.gridView1);
		tagButton = (ImageButton) view.findViewById(R.id.button_tag);
		headerbg = (ImageView) view.findViewById(R.id.header_bg);
		messageButton = (Button) view.findViewById(R.id.button_message);
		tagButton.setOnClickListener(this);
		messageButton.setOnClickListener(this);
		ll_footView = (LinearLayout)getView().findViewById(R.id.ll_footer);
		loginButton = (ImageButton)getView().findViewById(R.id.login_button);
		loginButton.setOnClickListener(this);
		regButton = (ImageButton)getView().findViewById(R.id.register_button);
		regButton.setOnClickListener(this);
		imageLoader = new ImageLoader(context);
	}

	private void initData(String ctagid) {
		tagid = ctagid;
		tagList.clear();
		Tag tag = new Tag();
		tag.setTagid("");
		tag.setTagname("全部");
		tagList.add(0, tag);
//		if (CacheService.isLogined()) {
//			tagList.addAll(DataService.getTagList());
//		}	
		tagList.addAll(DataService.getTagList());
	//	beginToload = getActivity().getIntent().getBooleanExtra("beginToload", false);
		gridAdapter = new TagListAdapter(context, tagList);
		gridAdapter.setTagId(tagid);
		gridView.setAdapter(gridAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
//				Intent intent = new Intent(getActivity(), IndexActivity.class);
//				intent.putExtra("default", CommunityFragment.TAG);
//				intent.putExtra("tagid", tagList.get(arg2).getTagid());
//				//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//				getActivity().startActivity(intent);
//				getActivity().finish();
//				beginToload = true;
				initData(tagList.get(arg2).getTagid());
				closeTagLayout();
				
			}
		});
		if (CacheService.isLogined()) {
			adapter = new CommunityListAdapter(context, list, 
					CacheService.getSpace().getXiaoquid());
	//		getNewMsgCount();                 //获取未读信息数量
		} else {
			adapter = new CommunityListAdapter(context, list, 
					xiaoquid = getActivity().getIntent().getStringExtra("xiaoquid"));
		}
		
		listView.setAdapter(adapter);
		listView.setonRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				isRefresh = true;
				page = 0;
				getXiaoqu();
				if (CacheService.isLogined()) {
					countTask = new CountMsgTask().execute();
				}
				
			}
		});
		listView.setOnScrollStopAndEndListener(new OnScrollStopAndEndListener() {
			@Override
			public void onEndAndStopScroll() {
				if (!isLoading) {
					getXiaoqu();
				}
			}
		});
		adapter.setOnTagClickInterface(new OnTagClickInterface() {
			
			@Override
			public void onTagChange(String ctagid) {
				// TODO Auto-generated method stub
	//			beginToload = true;
				initData(ctagid);
			}
		});
		 listView.goLoading();
		if (CacheService.isLogined()) {
			ll_footView.setVisibility(View.GONE);
			Space space = CacheService.getSpace();
			xiaoquid = space.getXiaoquid();
			xiaoquname = space.getXiaoquname();
			headerTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			imageLoader.DisplayImage(space.getPic_url(), headerbg,
					R.drawable.theme, 0, 0);				    	
		} else {
			ll_footView.setVisibility(View.VISIBLE);
			
			xiaoquid = getActivity().getIntent().getStringExtra("xiaoquid");
			xiaoquname = getActivity().getIntent().getStringExtra("xiaoquname");
			picUrl = getActivity().getIntent().getStringExtra("picUrl");
			if (picUrl != null)
				imageLoader.DisplayImage(picUrl, headerbg, R.drawable.theme, 0,
						0);
			
			
		}
		headerTitle.setText(xiaoquname);
		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) headerbg
				.getLayoutParams();
		params.height = getActivity().getWindowManager().getDefaultDisplay()
				.getHeight() / 3;
		headerbg.setLayoutParams(params);
		
	}
	class CountMsgTask extends AsyncTask<Void,String,String>{
		long messageCount;
		long pmcount;
		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			try {
				messageCount = SpaceService.noticecount(); 
				pmcount = CpService.pmcount();
			} catch (MyHttpException e) {
				// TODO Auto-generated catch block
				return e.getErrorMessage();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if (result == null) {
				if (messageCount > 0 || pmcount > 0) {
					messageButton.setVisibility(View.VISIBLE);
					messageButton.setText("您有" + (messageCount + pmcount) + "未读信息");;
					IndexActivity.activity.numBtn.setVisibility(View.VISIBLE);
					IndexActivity.activity.numBtn.setText((messageCount) + pmcount +"");
				} else {
					messageButton.setVisibility(View.GONE);
					IndexActivity.activity.numBtn.setVisibility(View.GONE);
				}
				
			} else {
				((BaseActivity)getActivity()).showMessage(result);
			}
			super.onPostExecute(result);
		}

	}

	class MyOnLoadFinish implements onLoadingFinishListener {
		@Override
		public void onFinish(Bitmap bitmap, ImageView imageView, List<View> list) {
			if (bitmap != null) {
				float h = bitmap.getHeight();
				float w = bitmap.getWidth();
				headerHeight = (int) (h / w * imageView.getWidth());
				LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageView
						.getLayoutParams();
				params.height = headerHeight;
				imageView.setLayoutParams(params);
				imageView.setImageBitmap(bitmap);
			}
		}
	}
	

	private void getXiaoqu() {
		task = new ListTask().execute();
		
	}
	class ListTask extends AsyncTask<Void, Void, Void> {
		List<Community> aList;
		

		@Override
		protected void onPreExecute() {
			isLoading = true;
			page++;
			if (!isRefresh) {
				listView.addFooterView(footView);
				listView.removeFooterView(nodataView);
			}
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				aList = SpaceService.home(xiaoquid, tagid, page + "", "", "",
						"");
				
			} catch (MyHttpException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			
			if (result == null) {
				if (isRefresh) {
					isRefresh = false;
					list.clear();
					listView.onRefreshComplete();
				}else{
					listView.removeFooterView(footView);
				}
				if (aList != null) {
					list.addAll(aList);
				} else {
					listView.addFooterView(nodataView);
					if (list.size() == 0) {
						footerText.setText("这个标签还没有内容哟");
					} else {
						footerText.setText("没有更多内容");
					}
				}			
				
				adapter.notifyDataSetChanged();
			}
			isLoading = false;
			super.onPostExecute(result);
		}
	}

	@Override
	public void onClick(View v) {
		if (v == menuButton) {
			if (viewActionsContentView.isActionsShown()) {
				viewActionsContentView.showContent();
			} else {
				viewActionsContentView.showActions();
			}
		} else if (v == postButton) {
			if (((BaseActivity) getActivity()).checkLogin()) {
				Intent intent = new Intent(context, PostActivity.class);
				intent.putExtra("idtype", "talkid");
				intent.putExtra("isFromCommunity", true);
				startActivity(intent);
			}
		} else if (v == headerTitle) {
			if (!CacheService.isLogined()) {
				Intent intent = new Intent(context, LoginMapActivity.class);
				startActivity(intent);
				getActivity().finish();
			}
		} else if (v == telephoneButton) {
			if(CacheService.isLogined()) {
			      Intent intent = new Intent(context, TelephoneActivity.class);
			      startActivity(intent);
			} else {
				xiaoquid = getActivity().getIntent().getStringExtra("xiaoquid");
				Intent intent = new Intent(context, TelephoneActivity.class);
				intent.putExtra("xiaoquid", xiaoquid);
				startActivity(intent);
			}
		} else if (v == tagButton) {
			if (tagIsOpen) {
				closeTagLayout();
			} else {
				openTagLayout();
			}
		} else if (v == messageButton) {
			Intent intent = new Intent(getActivity(), MsgListActivity.class);
			getActivity().startActivity(intent);
			messageButton.setVisibility(View.GONE);
			getActivity().finish();
		} else if (v == regButton) {
			Intent intent = new Intent(context, RegFirstActivity.class);
			startActivity(intent);
		} else if (v == loginButton) {
			Intent intent = new Intent(context, LoginActivity.class);
			startActivity(intent);
		}
	}

	private void openTagLayout() {
		new Handler().postDelayed(new Runnable() {
			public void run() {
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						int height = gridView.getHeight();
						if (height <= AndroidUtil.dpToPx(116, context)) {
							LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) gridView
									.getLayoutParams();
							params.height = height + 30;
							gridView.setLayoutParams(params);
							openTagLayout();
						} else {
							tagIsOpen = true;
						}
					}
				});
			}
		}, 10);
	}

	private void closeTagLayout() {
		new Handler().postDelayed(new Runnable() {
			public void run() {
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						int height = gridView.getHeight();
						if (height > 0) {
							LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) gridView
									.getLayoutParams();
							params.height = height - 30;
							gridView.setLayoutParams(params);
							closeTagLayout();
						} else {
							tagIsOpen = false;
						}
					}
				});
			}
		}, 10);
	}
}
